package Synchronized;

public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        Data data = new Data();
        new Thread(()->{
            //调用+1方法
            for(int i=0;i<10;i++){
                try {
                    data.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            //调用+1方法
            for (int i = 0; i < 10; i++) {
                try {
                    data.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            //调用+1方法
            for (int i = 0; i < 10; i++) {
                try {
                    data.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}
class Data {

    private int num = 0;
    public synchronized void incr() throws InterruptedException {
        while (num!=0){
            this.wait();
        }
        num++;
        //通知其他线程我+1完毕了
        System.out.println(Thread.currentThread().getName()+"->"+num);
        this.notify();
    }

    public synchronized void decr() throws InterruptedException {
        while (num == 0) {
            this.wait();
        }
        num--;
        //通知其他线程我-1完毕了
        System.out.println(Thread.currentThread().getName() + "->"+num);
        this.notify();
    }
}